<template>
  <div>
    <el-form
      :rules="rules"
      ref="formInline"
      :model="formInline"
      class="demo-form-inline"
      style="width: 800px; margin-left: 50px"
    >
      <el-form-item label="专题标题" class="inline-form-item" prop="title">
        <el-input v-model="formInline.title" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="专题子标题" class="inline-form-item" prop="subtitle">
        <el-input v-model="formInline.subtitle" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="专题图片" class="inline-form-item">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/storage/create"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="formInline.picUrl"
            :src="formInline.picUrl"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="专题内容" class="inline-form-item" prop="content">
        <div class="tinymce-editor">
          <editor
            v-model="formInline.content"
            :init="init"
            :disabled="disabled"
            @onClick="onClick"
          >
          </editor>
        </div>
      </el-form-item>
      <el-form-item label="商品低价" class="inline-form-item" prop="price">
        <el-input v-model="formInline.price" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="阅读量" class="inline-form-item">
        <el-input v-model="formInline.readCount" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="专题商品" class="inline-form-item">
        <el-button
          type="primary"
          size="mini"
          style="float: right"
          @click="build"
        >
          创建商品
        </el-button>
        <el-table border :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="商品ID" align="center">
          </el-table-column>
          <el-table-column prop="picUrl" label="图片" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.picUrl" width="40" height="30" alt="" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" align="center">
          </el-table-column>
          <el-table-column prop="brief" label="商品介绍" align="center">
          </el-table-column>
          <el-table-column prop="title" label="操作" align="center">
            <template #default="scope">
              <el-button
                size="mini"
                type="danger"
                @click="dels(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div
      style="display: flex; justify-content: flex-start; margin-top: 20px"
      :active-name="activeTab"
    >
      <el-button>取消</el-button>
      <el-button
        type="primary"
        name="add"
        v-if="activeTab === 'add'"
        @click="submit('formInline')"
        >确定</el-button
      >
      <el-button
        type="primary"
        name="add"
        v-if="activeTab === 'edit'"
        @click="submitt('formInline')"
        >确定</el-button
      >
    </div>
    <!------------------------------------------------------------------------- -->
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="50%">
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        style="margin-left: 50px"
      >
        <el-form-item>
          <el-input
            prop="form.goodsSn"
            v-model="form.goodsSn"
            style="width: 200px"
            size="mini"
            placeholder="请输入商品编号"
          ></el-input>
          <el-input
            prop="form.name"
            v-model="form.name"
            style="width: 200px"
            size="mini"
            placeholder="请输入商品名称"
          ></el-input
          ><el-button type="primary" size="mini" @click="find">
            查找
          </el-button>
        </el-form-item>
        <el-table
          border
          :data="info"
          style="width: 100%"
          size="mini"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="id" label="商品ID" align="center">
          </el-table-column
          ><el-table-column prop="picUrl" label="图片" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.picUrl" width="40" height="30" alt="" />
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="商品名称"
            width="210"
            align="center"
          >
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!flag" type="primary" @click="findadd"
          >确 定</el-button
        >
      </span>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="get.page"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="get.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findList,
  redact,
  artadd,
  artupdate,
  artdel,
  add,
  search,
} from "@/api/promotion";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/media"; // 插入视频插件
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/wordcount"; // 字数统计插件
import "tinymce/icons/default";
export default {
  components: {
    Editor,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    // 基本路径，默认为空根目录，如果你的项目发布后的地址为目录形式，
    // 即abc.com/tinymce，baseUrl需要配置成tinymce，不然发布后资源会找不到
    baseUrl: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default: "lists image media table wordcount",
    },
    toolbar: {
      type: [String, Array],
      default:
        "undo redo |  formatselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat",
    },
  },
  data() {
    return {
      formInline: {
        title: "",
        subtitle: "",
        picUrl: "",
        content: this.value,
        price: "",
        readCount: "",
        goods: [],
      },
      tableData: [],
      form: {
        goodsSn: "",
        name: "",
      },
      info: {},
      rules: {
        title: [
          { required: true, message: "专题标题不能为空", trigger: "blur" },
        ],
        subtitle: [
          { required: true, message: "专题子标题不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "专题内容不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "专题低价不能为空", trigger: "blur" },
        ],
      },
      get: {
        page: 1,
        limit: 5,
        sort: "add_time",
        order: "desc",
        goodsSn: "",
        name: "",
      },
      activeTab: "add",
      selectedGoods: [],
      total: 0,
      dialogVisible: false,
      flag: true,
      //富文本
      init: {
        language_url: `${this.baseUrl}/tinymce/langs/zh_CN.js`,
        language: "zh_CN",
        skin_url: `${this.baseUrl}/tinymce/skins/ui/oxide`,
        content_css: `${this.baseUrl}/tinymce/skins/content/default/content.css`,
        // skin_url: `${this.baseUrl}/tinymce/skins/ui/oxide-dark`, // 暗色系
        // content_css: `${this.baseUrl}/tinymce/skins/content/dark/content.css`, // 暗色系
        height: 300,
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: true,
        menubar: true,
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, success, failure) => {
          const img = "data:image/jpeg;base64," + blobInfo.base64();
          success(img);
        },
      },
      myValue: this.value,
    };
  },
  mounted() {
    tinymce.init({});
  },
  created() {
    const tab = this.$route.query.tab;
    if (tab === "edit") {
      this.activeTab = "edit";
      this.formInline = {
        title: this.$route.query.title,
        subtitle: this.$route.query.subtitle,
        picUrl: this.$route.query.picUrl,
        content: this.$route.query.content,
        price: this.$route.query.price,
        readCount: this.$route.query.readCount,
        goods: this.$route.query.goods,
      };
    } else {
      this.activeTab = "add";
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.formInline.picUrl = URL.createObjectURL(file.raw);
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          artadd(this.formInline).then((res) => {
            console.log(res);
          });
          this.$router.push({
            name: "thematicmanagement",
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitt(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          artupdate(this.formInline).then((res) => {
            console.log(res);
          });
          this.$router.push({
            name: "thematicmanagement",
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    build() {
      this.flag = false;
      this.dialogVisible = true;
    },
    find() {
      this.get.page = 1;
      this.get.goodsSn = this.form.goodsSn;
      this.get.name = this.form.name;
      findList(this.get).then((res) => {
        console.log(res);
        if ((res.data.errmsg = "成功")) {
          this.info = res.data.list;
          this.total = res.data.total;
          console.log(this.tableData);
        }
      });
    },
    findadd() {
      this.selectedGoods.forEach((goods) => {
        const isExist = this.tableData.some((item) => item.id === goods.id);
        if (!isExist) {
          this.tableData.push(goods); // 避免重复添加
          console.log(goods.id)
        }
      });
      this.dialogVisible = false;
    },
    handleSelectionChange(selection) {
      this.selectedGoods = selection;
    },
    dels(index, row) {
      this.tableData.splice(index, 1);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.get.limit = val;
      this.getdata();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.get.page = val;
      this.getdata();
    },
    //富文本
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = "";
    },
  },
  watch: {
    value(newValue) {
      this.myValue = newValue;
    },
    myValue(newValue) {
      this.$emit("input", newValue);
    },
  },
};
</script>

<style scoped>
.inline-form-item {
  display: flex;
  align-items: center;
}

::v-deep .inline-form-item .el-form-item__label {
  width: 100px;
  text-align: left;
  padding-right: 10px;
}

::v-deep .inline-form-item .el-form-item__content {
  flex: 1;
  margin-left: 0 !important;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
